﻿@page "/customClickHandler"

<div class="d-md-flex flex-md-row-reverse align-items-center justify-content-between">
    <a class="btn btn-sm btn-bd-light my-2 my-md-0" href="https://github.com/jdtcn/BlazorDateRangePicker/blob/master/Demo.Shared/Pages/CustomClickHandler.razor"
       title="View this file on GitHub" target="_blank" rel="noopener">View on GitHub</a>
    <h3>CustomClickHandler</h3>
</div>

<p>
    This example demonstrates how to override day click function to build custom functionality.
</p>

<p>
    In this example the start date can only be selected in the left calendar and the end date can only be selected in the right calendar.
</p>

<Example Text="@ExampleText">
    <DateRangePicker @ref="Picker" OnMonthChanged="MonthChanged" />
</Example>

@code {
    DateRangePicker Picker { get; set; }

    private void MonthChanged()
    {
        UpdateClickHandlers();
    }

    private void UpdateClickHandlers()
    {
        var days = Enumerable
            .Concat(Picker.LeftCalendar.Calendar, Picker.RightCalendar.Calendar)
            .SelectMany(d => d);

        foreach (var day in days)
        {
            var dayClick = day.Click;
            day.Click = () =>
            {
                if (day.Side == SideType.Right && !Picker.TEndDate.HasValue)
                {
                    if (day.Day > Picker.TStartDate) dayClick.Invoke();
                }
                else if (day.Side == SideType.Left)
                {
                    Picker.TStartDate = null;
                    Picker.TEndDate = null;
                    dayClick.Invoke();
                }
            };
        }
    }

    private string ExampleText = "<DateRangePicker @ref=\"Picker\" OnMonthChanged=\"MonthChanged\" />" +
@"

@code {

DateRangePicker Picker { get; set; }

private void MonthChanged()
{
    UpdateClickHandlers();
}

private void UpdateClickHandlers()
{
    var days = Enumerable
        .Concat(Picker.LeftCalendar.Calendar, Picker.RightCalendar.Calendar)
        .SelectMany(d => d);

    foreach (var day in days)
    {
        var dayClick = day.Click;
        day.Click = () =>
        {
            if (day.Side == SideType.Right && !Picker.TEndDate.HasValue)
            {
                if (day.Day > Picker.TStartDate) dayClick.Invoke();
            }
            else if (day.Side == SideType.Left)
            {
                Picker.TStartDate = null;
                Picker.TEndDate = null;
                dayClick.Invoke();
            }
        };
    }
}
";

}
